package com.hmdp.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collection;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


public class SimpleLock implements ILock{
    private String name;
    private final StringRedisTemplate stringRedisTemplate;

    public SimpleLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }
    private final String ID_PREFIX = UUID.randomUUID()+"-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT =new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unLock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        String id = ID_PREFIX+Thread.currentThread().getId();
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent("lock:" + name, id, timeoutSec,
                TimeUnit.SECONDS);

        return flag;
    }
    @Override
    public void unLock() {
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList("lock:" + name),ID_PREFIX+Thread.currentThread().getId());
    }
    /*
    @Override
    public void unLock() {
        String id = ID_PREFIX+Thread.currentThread().getId();
        String flag = stringRedisTemplate.opsForValue().get("lock:" + name);
        if(id.equals(flag)) {
            stringRedisTemplate.delete("lock" + name);
        }
    }

     */
}
